<template>
  <div class="">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <!-- <el-breadcrumb-item><a>用户管理</a></el-breadcrumb-item> -->
      <el-breadcrumb-item>部门管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 头部搜索 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="queryParams.deptName" placeholder="请输入部门名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <!-- <el-form-item label="父菜单ID" prop="parentId">
        <el-input v-model="queryParams.parentId" placeholder="请输入父菜单ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 按钮 -->
      <el-row :gutter="10" class="mb8" style="marginBottom:20px">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addDeptHandle">新增</el-button>
        </el-col>
        <!-- right-toolbar  百度:显示/隐藏列操作按钮-->
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
      </el-row>

      <!-- 表格 -->
      <el-table v-if="refreshTable" :default-expand-all="isExpandAll" :data="userList"
        style="width: 100%;margin-bottom: 20px;" row-key="deptId" border
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="deptName" label="部门名称">
        </el-table-column>
        <!-- <el-table-column prop="status" label="排序">
        </el-table-column> -->
        <el-table-column prop="leaderName" label="部门负责人" width="200"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <span :value="scope.row.status">{{ scope.row.status === '0' ? '正常' : '停用' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template v-if="scope.row.userId !== 1" slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-plus" @click="addDeptHandle(scope.row)">新增</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="editDeptHandler(scope.row)">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" v-if="scope.row.parentId !== 0"
              @click="deleteDeptHandle(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :before-close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="18">
            <el-form-item label="是否顶级" prop="isOrTopDept">
              <el-radio-group v-model="form.isOrTopDept" :disabled="isDisabled">
                  <el-radio label="0">顶级部门</el-radio>
                  <el-radio label="1">非顶级部门</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" v-if="form.isOrTopDept==='1'">
            <el-form-item label="上级部门" prop="parentId" >
              <!-- <v-tree-select :data="deptOption" value-field-name="id" v-model="form.parentId"></v-tree-select> -->
              <el-cascader
                placeholder="请选择上级部门"
                style="width: 100%;"
                ref="cascaderHandle"
                :options="deptOption"
                :disabled="isDisabled"
                :props="{ checkStrictly: true }"
                v-model="form.parentId"
                @change="handleCascaderChange"
                filterable
                clearable></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-select v-model="form.leader" filterable placeholder="请输入负责人">
                <el-option v-for="item in leaderOptions" :key="item.userId" :label="item.userName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态" prop="status">
              <!-- <el-radio-group v-model="form.status"> -->
              <el-radio-group v-model="form.status">
                <el-tooltip effect="dark" content="请手动设置需要开启的账号">
                  <el-radio label="0">正常</el-radio>
                </el-tooltip>
                <el-tooltip effect="dark" content="该部门下所有账号均会停用">
                  <el-radio label="1">停用</el-radio>
                </el-tooltip>
              </el-radio-group>
              <!-- </el-radio-group> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import Treeselect from "@riophae/vue-treeselect";
// import "@riophae/vue-treeselect/dist/vue-treeselect.css";
// import VTreeSelect from 'vue-treeselect'

export default {
  name: "Menu",
  // components: {
  //   VTreeSelect
  // },
  data() {
    return {
      menuOptions: [],
      // 部门树选项
      deptOption: [],
      newDeptOption:[],
      options: [{
        value: '0',
        label: '正常'
      }, {
        value: '1',
        label: '停用'
      }],
      hasChildren: true,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      currentPage4: 1,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 20,
      // 菜单权限表格数据
      menuList: [],
      deptId: undefined,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        deptName: undefined, // 部门名称
        status: undefined // 状态
      },
      radio: 1,
      // 重新渲染表格状态
      refreshTable: true,
      // 对话框显示与隐藏
      dialogVisible: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // // 设置上传的请求头部
        // headers: { Authorization: 'Bearer ' + getToken() },
        // // 上传的地址
        // url: process.env.VUE_APP_BASE_API + '/system/user/importData'
      },
      // 表单参数
      form: {
        status: '0',
        isOrTopDept:'1',
      },
      isDisabled: false,
      // 表单校验
      rules: {
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" }
        ],
        //部门状态不能为空
        status: [
          { required: true, message: "部门状态不能为空", trigger: "blur" }
        ],
        //上级部门不能为空
        parentId: [
          { required: true, message: "上级部门不能为空", trigger: "blur" }
        ],
        isOrTopDept: [
          { required: true, message: "判断是否为顶级部门不能为空", trigger: "blur" }
        ],
      },
      userList: [],
      leaderOptions: []
    };
  },
  created() {
    this.getList();
    this.getOptions();
  },
  methods: {
    handleCascaderChange(){
      this.$refs.cascaderHandle.dropDownVisible = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.deptOption = this.newDeptOption //恢复默认的部门树
      this.reset();
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    /** 查询部门列表 */
    async getList() {
      const { data: res } = await this.$http.post('/sys-dept/page', this.queryParams)
      if (res.code === 20000) {
        let newarr= [...res.data]
        function convertToTreeData(data) {
          const treeData = [];
          function convert(dept) {
            const node = {
              value: dept.deptId,
              label: dept.deptName,
              children: []
            };
            if (dept.children && dept.children.length > 0) {
              dept.children.forEach(child => {
                node.children.push(convert(child));
              });
            }
            return node;
          }
          data.forEach(root => {
            treeData.push(convert(root));
          });
          return treeData;
        }
        const arr = convertToTreeData(newarr)
        this.deptOption = arr;
        this.newDeptOption = [...arr];
        this.userList = res.data
      }
    },
    async getOptions() {
      const { data: res } = await this.$http.post('/sys-user/page', {
        currentPage: 1,
        pageSize: -1
      })
      if (res.code === 20000) {
        this.leaderOptions = res.data.records
      } else {
        this.$message.error(res.msg)
      }
    },
    // 表单重置
    reset() {
      this.form= {
        status: '0',
        isOrTopDept:'1',
      }
      this.isDisabled=false
    },

    // 新增按钮
    addDeptHandle(row) {
      this.open = true;
      this.title = "添加部门"
      if (row != null) {
        this.form.parentId = row.deptId
        this.form.isOrTopDept = '1'
      }
    },

    // 修改按钮 修改用户
    editDeptHandler(row) {
      // this.deptId = row.deptId
      // this.dialogVisible = true
      this.open = true;
      this.isDisabled=true
      let arr = JSON.parse(JSON.stringify(this.deptOption));
      //arr 是一树型结构，我想让arr的value== row.deptId 的那一项 加上disabled: true
      function disableItem(arr, deptId) {
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].value == deptId) {
                arr[i].disabled = true;
            }
            if (arr[i].children) {
                disableItem(arr[i].children, deptId);
            }
        }
      }
      disableItem(arr, row.deptId);
      this.deptOption = arr;
      if(row.parentId == 0){
        this.form = { 
        ...row,
        isOrTopDept: '0'
       }
      }else{
        this.form = { 
        ...row,
        isOrTopDept: '1'
       }
      }
      
      this.title = "修改部门"
    },
    // 删除封装
    async deleteDeptHandle(row) {
      if (!(await this._box(row.deptId, 'get', '/sys-dept/delete', 'deptId'))) return;
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          if (this.form.deptId != undefined) {
            const params = this.form
            if(params.isOrTopDept=='0'){
              params.parentId=0
            }
            if(Array.isArray(params.parentId)){
              params.parentId=this.form.parentId[this.form.parentId.length-1]
             }
            const { data: res } = await this.$http.post('/sys-dept/saveOrUpdate', params)
            if (res.code === 20000) {
              this.$message.success(`修改成功!`)
              this.open = false
              this.reset()
              this.getList()
              this.deptOption = this.newDeptOption //恢复默认的部门树
            } else {
              this.$message.error(res.msg)
            }
          } else {
             const params = this.form
             if(Array.isArray(params.parentId)){
              params.parentId=this.form.parentId[this.form.parentId.length-1]
             }
              console.log(this.form,'参数');
            const { data: res } = await this.$http.post('/sys-dept/saveOrUpdate', params)
            if (res.code === 20000) {
              this.$message.success(`新增成功!`)
              this.open = false
              this.$refs.form.resetFields()
              this.reset()
              this.getList()
              this.deptOption = this.newDeptOption //恢复默认的部门树
            } else {
              this.$message.error(res.msg)
            }
          }
        }
      });
    },

    // 监听添加用户对话框关闭事件
    addDialogClosed() {
      this.$refs.form.resetFields() // 重置表单
    },



    /** 搜索按钮操作 */
    handleQuery() {
      // this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.menuId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const menuIds = row.menuId || this.ids;
      this.$modal.confirm('是否确认删除菜单权限编号为"' + menuIds + '"的数据项？').then(function () {
        return delMenu(menuIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/menu/export', {
        ...this.queryParams
      }, `menu_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
